package net.meilly.learn.demo.springboot.websocket.controller;

import lombok.extern.slf4j.Slf4j;
import net.meilly.learn.demo.springboot.websocket.vo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

/**
 * @Description
 * @Author Wang.sj
 * @Data 2023/10/16 17:33
 */
@Slf4j
@Controller
public class WebSocketController {

    // 实现向浏览器发送消息的功能
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;


    @MessageMapping("/send")
    public void handleHelloMessage(@Payload Message message) {
        log.info("【收到消息】：{}", message);
        switch (message.getType()) {
            case JOIN, LEAVE -> publicMessage(message);
            case CHAT -> simpMessagingTemplate.convertAndSendToUser("hank", "/to/user/message", message);   // 将会发送到将“/user/hank/to/user/message”目的地上
//            case CHAT -> simpMessagingTemplate.convertAndSend("/topic/messages", message);                                // 将会发送到将“/topic/messages”目的地上
            default -> System.out.println("不支持的消息类型");
        }
    }

    @MessageMapping("/news/notify/all")
    @SendTo("/topic/messages")
    public Message publicMessage(Message message) {
        return message;
    }
}
